package com.sk.bilibili.apiMapper;

import com.sk.bilibili.apiMapper.component.ClassBuilder;
import lombok.SneakyThrows;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Set;

/**
 * @author 邵康
 * @date 2021/7/11 18:18
 */
public class ApiFrame extends JFrame implements ActionListener {

    public static void main(String[] args) {
        new ApiFrame();
    }

    public ApiFrame() throws HeadlessException {
        beforeInitComponent();
        initComponent();
        afterInitComponent();
    }

    private void afterInitComponent() {
        setVisible(true);
    }

    private void beforeInitComponent() {
        setSize(600,400);
        setTitle("Json路径选择器");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    }

    private JButton create;
    private JButton copy;
    private JTree tree;
    private Clipboard clipboard;
    private static final String DEFAULT_JSON="{\"code\":200,\"message\":\"成功\",\"data\":[{\"id\":1,\"url\":\"https://www.bilibili.com/\",\"imgUrl\":\"//i0.hdslb.com/bfs/feed-admin/d8884aeafa89af5d749cc71eaa2987f169286499.jpg@880w_388h_1c_95q\",\"title\":\"一年一次！竟然有这么多up凑在一起？\"},{\"id\":2,\"url\":\"https://www.bilibili.com/\",\"imgUrl\":\"//i0.hdslb.com/bfs/feed-admin/b2ca0f282180c33b86f0537f7112d82de570772a.jpg@880w_388h_1c_95q\",\"title\":\"投稿剧本杀，赢取10万元！！\"},{\"id\":3,\"url\":\"https://www.bilibili.com/\",\"imgUrl\":\"https://i0.hdslb.com/bfs/sycp/creative_img/202107/72fa6e4081496ae21ca048710f3d9a51.jpg@880w_388h_1c_95q\",\"title\":\"古剑全新系列RPG手游\"},{\"id\":4,\"url\":\"https://www.bilibili.com/\",\"imgUrl\":\"//i0.hdslb.com/bfs/feed-admin/983c3e0c2120d96c69a2a8e8efe0e9c768f0baa9.jpg@880w_388h_1c_95q\",\"title\":\"那一天，死亡预言冲上热搜——\"},{\"id\":5,\"url\":\"https://www.bilibili.com/\",\"imgUrl\":\"//i0.hdslb.com/bfs/feed-admin/36564cf26b03b1b92954a540f5ea4605fe07ea7c.jpg@880w_388h_1c_95q\",\"title\":\"国风幻想动画震撼开播！\"}]}";

    private void initComponent() {
        JPanel bottom = new JPanel(new FlowLayout());
        create=new JButton("从剪切板创建");
        create.addActionListener(this);
        bottom.add(create);
        copy=new JButton("复制到剪切板");
        copy.addActionListener(this);
        bottom.add(copy);
        add(bottom,BorderLayout.SOUTH);
        createTree(DEFAULT_JSON);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==create){
            reCreate();
        }else if(e.getSource()==copy){
            setCopy();
        }
    }

    private void setCopy() {
        TreePath[] paths = tree.getSelectionPaths();
        if(paths==null){
            JOptionPane.showMessageDialog(this,"没有选中任何节点!","错误!",JOptionPane.ERROR_MESSAGE);
            return;
        }
        ClassBuilder classBuilder = new ClassBuilder(paths);
        String clazz=classBuilder.build();
        clipboard.setContents(new StringSelection(clazz),null);
        JOptionPane.showMessageDialog(this,"已经粘贴到剪切板","提示!",JOptionPane.INFORMATION_MESSAGE);
    }

    @SneakyThrows
    private void reCreate() {
        if(clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)){
            String json = (String) clipboard.getData(DataFlavor.stringFlavor);
            createTree(json);
        }else {
            JOptionPane.showMessageDialog(this,"剪切板为空!","错误!",JOptionPane.ERROR_MESSAGE);
        }
    }

    private void createTree(String json) {
        if(tree!=null)remove(tree);
        try {
            JSONObject object = new JSONObject(json);
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("ROOT");
            buildTree(root,object);
            tree=new JTree(root);
            add(tree);
            validate();
            repaint();
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this,"JSON格式错误!","错误!",JOptionPane.ERROR_MESSAGE);
        }
    }

    private void buildTree(DefaultMutableTreeNode root, JSONObject object) throws Exception{
        Set<String> set = object.keySet();
        for (String key:set){
            Object value = object.get(key);
            if(value instanceof JSONArray){
                if(((JSONArray) value).length()==0)continue;
                key="$"+key;
                value=((JSONArray) value).get(0);
            }
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(key);
            root.add(node);
            if(value instanceof JSONObject){
                buildTree(node, (JSONObject) value);
            }
        }
    }

}
